package com.avecsys.quotemanager.mbeans.supplier;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.icefaces.ace.json.JSONException;
import org.icefaces.ace.json.JSONObject;

import com.avecsys.quotemanager.dao.common.EnumTransactionStatus;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.mbeans.core.BaseMBean;
import com.avecsys.quotemanager.pojos.SupplierMasterPojo;
import com.avecsys.quotemanager.pojos.UserMasterPojo;
import com.avecsys.quotemanager.service.supplier.SupplierMasterService;
import com.avecsys.quotemanager.service.user.UserMasterService;
import com.avecsys.quotemanager.ui.components.MessageDialog;

/**
 * @author Sam Sundar
 * 
 */
public class SupplierUsersListMBean extends BaseMBean implements Serializable {
	private final Log log = LogFactory.getLog(SupplierUsersListMBean.class);

	private SupplierMasterPojo selectedSupplier;

	private SupplierMasterService supplierMasterService;

	private UserMasterService userMasterService;

	private List<UserMasterPojo> userMasterPojoList = new ArrayList<UserMasterPojo>();

	public SupplierUsersListMBean() {
		super();
	}

	/**
	 * Action method to open the add user screen for a supplier
	 * 
	 * @return String
	 */
	public String actionAddUser() {
		FacesContext faceContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = faceContext.getExternalContext()
				.getRequestParameterMap();
		String selectedSupplierId = paramValues.get("selectedSupplierId");
		String selectedSupplierCompanyName = paramValues
				.get("selectedSupplierCompanyName");
		SupplierUsersMBean supplierUsersMBean = (SupplierUsersMBean) faceContext
				.getApplication().evaluateExpressionGet(faceContext,
						"#{supplierUsersMBean}", SupplierUsersMBean.class);
		supplierUsersMBean.setSelectedSupplierId(selectedSupplierId);
		supplierUsersMBean
				.setSelectedSupplierCompanyName(selectedSupplierCompanyName);
		supplierUsersMBean.setUserMasterPojo(new UserMasterPojo());
		return "openAddUserForSupplier";
	}

	public String actionCancel() {
		return "openListAllSuppliers";
	}

	/**
	 * Method to show the confirm dialog request to delete supplier user
	 * 
	 * @param actionEvent
	 */
	public void confirmDeleteAction(ActionEvent actionEvent) {
		FacesContext faceContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = faceContext.getExternalContext()
				.getRequestParameterMap();
		String userId = (String) paramValues.get("userId");
		String selectedSupplierId = (String) paramValues
				.get("selectedSupplierId");
		String userName = (String) paramValues.get("userName");
		JSONObject requestJSONObject = new JSONObject();
		try {
			requestJSONObject.put("supplierId", selectedSupplierId);
			requestJSONObject.put("userId", userId);
			requestJSONObject.put("companyName", userName);
			getMessageDialog().setRequestJSON(requestJSONObject.toString());
			getMessageDialog().setMessage(
					"Are you sure to delete '" + userName + "' ?");
		} catch (JSONException e) {
			log.error(e);
		}
		getMessageDialog().showDialog();
	}

	/**
	 * Method to delete the selected supplier user
	 * 
	 * @param actionEvent
	 */
	public void deleteSupplierUser(ActionEvent actionEvent) {
		FacesContext faceContext = FacesContext.getCurrentInstance();
		String requestJSON = getMessageDialog().getRequestJSON();
		JSONObject requestJSONObject;
		String userId = null;
		String supplierId = null;
		try {
			requestJSONObject = new JSONObject(requestJSON);
			userId = (String) requestJSONObject.get("userId");
			supplierId = (String) requestJSONObject.get("supplierId");
			SupplierMasterPojo supplierMasterPojo = supplierMasterService
					.getSupplierMasterById(new Long(supplierId));
			Integer transactionStatus = userMasterService.deleteSupplierUser(
					supplierMasterPojo, new Long(userId));
			if (transactionStatus.intValue() == EnumTransactionStatus.SUCESS
					.ordinal()) {
				loadAllUsersBySupplier(supplierMasterPojo);
				FacesMessage facesMessage = new FacesMessage(
						FacesMessage.SEVERITY_INFO,
						"Selected User sucessfully deleted.", null);
				faceContext.addMessage("messageBoardId", facesMessage);
			} else {
				FacesMessage facesMessage = new FacesMessage(
						FacesMessage.SEVERITY_ERROR,
						"Selected User failed to delete.", null);
				faceContext.addMessage("messageBoardId", facesMessage);
			}
		} catch (BusinessException e) {
			log.error(e);
		} catch (Exception e) {
			log.error(e);
		}
		getMessageDialog().hideDialog();
	}

	/**
	 * Edits the supplier user information
	 * 
	 * @return
	 */
	public String editSupplierUser() {
		FacesContext faceContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = faceContext.getExternalContext()
				.getRequestParameterMap();
		String selectedSupplierId = paramValues.get("selectedSupplierId");
		String selectedSupplierCompanyName = paramValues
				.get("selectedSupplierCompanyName");
		String userId = (String) paramValues.get("userId");
		try {
			SupplierUsersMBean supplierUsersMBean = (SupplierUsersMBean) faceContext
					.getApplication().evaluateExpressionGet(faceContext,
							"#{supplierUsersMBean}", SupplierUsersMBean.class);
			supplierUsersMBean.setSelectedSupplierId(selectedSupplierId);
			supplierUsersMBean
					.setSelectedSupplierCompanyName(selectedSupplierCompanyName);
			UserMasterPojo userMasterPojo = userMasterService
					.getUserMasterById(Long.parseLong(userId));
			supplierUsersMBean.setUserMasterPojo(userMasterPojo);
			supplierUsersMBean.setScreenModeEdit(true);
		} catch (BusinessException e) {
			log.error(e);
		} catch (Exception e) {
			log.error(e);
		}
		return "openEditUserForSupplier";
	}

	/**
	 * @return the selectedSupplier
	 */
	public SupplierMasterPojo getSelectedSupplier() {
		return selectedSupplier;
	}

	/**
	 * @return the supplierMasterService
	 */
	public SupplierMasterService getSupplierMasterService() {
		return supplierMasterService;
	}

	/**
	 * @return the userMasterPojoList
	 */
	public List<UserMasterPojo> getUserMasterPojoList() {
		return userMasterPojoList;
	}

	/**
	 * @return the userMasterService
	 */
	public UserMasterService getUserMasterService() {
		return userMasterService;
	}

	/**
	 * Method to load all the users for a supplier
	 * 
	 * @param supplierMasterPojo
	 * @throws BusinessException
	 */
	public void loadAllUsersBySupplier(SupplierMasterPojo supplierMasterPojo)
			throws BusinessException {
		setUserMasterPojoList(supplierMasterService
				.getAllUsers(supplierMasterPojo));
		setSelectedSupplier(supplierMasterPojo);
	}

	/**
	 * @param selectedSupplier
	 *            the selectedSupplier to set
	 */
	public void setSelectedSupplier(SupplierMasterPojo selectedSupplier) {
		this.selectedSupplier = selectedSupplier;
	}

	/**
	 * @param supplierMasterService
	 *            the supplierMasterService to set
	 */
	public void setSupplierMasterService(
			SupplierMasterService supplierMasterService) {
		this.supplierMasterService = supplierMasterService;
	}

	/**
	 * @param userMasterPojoList
	 *            the userMasterPojoList to set
	 */
	public void setUserMasterPojoList(List<UserMasterPojo> userMasterPojoList) {
		this.userMasterPojoList = userMasterPojoList;
	}

	/**
	 * @param userMasterService
	 *            the userMasterService to set
	 */
	public void setUserMasterService(UserMasterService userMasterService) {
		this.userMasterService = userMasterService;
	}
}
